package com.butterfly.hotkey.client.core.service;

import cn.hutool.core.util.StrUtil;
import com.butterfly.hotkey.client.core.HotkeyStore;
import com.butterfly.hotkey.core.model.HotKeyModel;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;

import java.net.InetSocketAddress;

/**
 * 处理各种worker netty的数据
 *
 * @author butterfly
 * @since 2025/2/18
 */
public class NettyService {

    private final HotkeyStore hotkeyStore;
    private final WorkerService workerService;

    public NettyService(WorkerService workerService, HotkeyStore hotkeyStore) {
        this.workerService = workerService;
        this.hotkeyStore = hotkeyStore;
    }

    /**
     * 处理新来的key事件
     *
     * @param hotKeyModel hotKeyModel
     */
    public void handleNewKey(HotKeyModel hotKeyModel) {
        String key;
        if (hotKeyModel == null || StrUtil.isBlank((key = hotKeyModel.getKey()))) {
            return;
        }

        // 如果是删除key，删除缓存，路径： dashboard -> worker -> client
        boolean remove = hotKeyModel.isRemove();
        if (remove) {
            hotkeyStore.remove(key);
            return;
        }

        // 如果是新增的hotkey，本地进行缓存 worker -> client
        hotkeyStore.markHotkey(key);
    }

    /**
     * 处理worker断链
     *
     * @param ctx ctx
     */
    public void handleWorkerInactive(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        InetSocketAddress socketAddress = (InetSocketAddress) channel.remoteAddress();
        String address = socketAddress.getHostName() + ":" + socketAddress.getPort();
        workerService.dealChannelInactive(address);
    }
}
